package com.silences.servlet;

import com.alibaba.fastjson.JSON;
import com.silences.pojo.Buyer;
import com.silences.service.BuyerService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.ServerException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

//登录接口
@WebServlet("/buyerlogin") //设置接口路径
public class BuyerLoginServlet extends HttpServlet {
    //extends 继承 HttpServlet类

    //get 请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
       doPost(req,resp);
    }


    //post 请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServerException,IOException {

        //post 请求优点  1 接收的数据量比较大  2 数据相对安全的

        //获取前端传递参数
        String buyername=req.getParameter("buyername");
        String password=req.getParameter("password");



        //调用业务层方法
        BuyerService buyerService =new BuyerService();
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            Map<String,Object> map = buyerService.getBuyers(buyername,"1","1");
            List<Buyer> list=(List<Buyer>)map.get("data");
            if(list != null && list.size()>0) {
                Buyer u = list.get(0);
                if (u.getPassword().equals(password)) {

                    map.put("code", "0000");
                    map.put("msg", "登录成功");
                    //在服务器中，保存用户名
                    req.getSession().setAttribute("buyername", list.get(0).getBuyername());
                    req.getSession().setAttribute("id",list.get(0).getId());
                    req.getSession().setAttribute("buyerplace",list.get(0).getBuyerplace());
                    req.getSession().setAttribute("buyernum",list.get(0).getBuyernum());
                } else {
                    map.put("code", "0001");
                    map.put("msg", "密码不正确");

                   }
                 }else{
                    map.put("code", "0001");
                    map.put("msg", "用户不存在");
                 }
            //返回数据给前端
            resp.getWriter().write(JSON.toJSON(map).toString());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
